<template>
  <div class="app-container">
    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="分类编码" prop="cateCodeLike">
            <el-input v-model="queryParams.cateCodeLike" placeholder="请输入分类编码" clearable size="default"
                      style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类名称" prop="cateNameLike">
            <el-input v-model="queryParams.cateNameLike" placeholder="请输入分类名称" clearable size="default"
                      style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属命名空间" prop="cateNamespaceLike">
            <el-input v-model="queryParams.cateNamespaceLike" placeholder="请输入所属命名空间" clearable size="default"
                      style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="分类标签" prop="cateLabelLike">
            <el-input v-model="queryParams.cateLabelLike" placeholder="请输入分类标签" clearable size="default"
                      style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <search-button @click="handleQuery" :perm="['uni:category:info:search']" />
            <reset-button @click="resetQuery" :perm="['uni:category:info:search']" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['uni:category:info:insert']" :roleType="['app']" />
      <delete-button @click="handleDelete" :disabled="multiple" :perm="['uni:category:info:delete']"
                     :roleType="['app']" />
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" :perm="['uni:category:info:search']" />
    </el-row>

    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" row-key="cateId"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类编码" prop="cateCode" align="center" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="分类名称" prop="cateName" align="center" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="所属命名空间" prop="cateNamespace" align="center" :show-overflow-tooltip="true" min-width="100">
        <template #default="scope">
          {{ selectDictLabel(cateNamespaceOptions, scope.row.cateNamespace)}}
        </template>
      </el-table-column>
      <el-table-column label="分类标签" prop="cateLabel" align="center" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="更新者" prop="updateBy" align="center" width="120" />
      <el-table-column label="更新时间" prop="updateTime" align="center" width="160" />
      <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width"
                       v-if="hasRoleType(['app'])">
        <template #default="scope">
          <text-add-button @click="handleAdd(scope.row)" :perm="['uni:category:info:insert']" :roleType="['app']" />
          <text-edit-button @click="handleUpdate(scope.row)" :perm="['uni:category:info:update']" :roleType="['app']" />
          <text-delete-button @click="handleDelete(scope.row)" :perm="['uni:category:info:delete']" :roleType="['app']"
                              :title="'是否确认删除记录' + scope.row.cateId + '?'" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增或修改对话框 -->
    <drag-dialog v-el-drag-dialog :title="editForm.title" :close-on-click-modal="false" v-model="editForm.open"
                 width="800px" append-to-body>
      <el-form ref="formRef" :model="editForm.data" :rules="editForm.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类编码" prop="cateCode">
              <el-input v-model="editForm.data.cateCode" placeholder="请输入分类编码" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类名称" prop="cateName">
              <el-input v-model="editForm.data.cateName" placeholder="请输入分类名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="父分类" prop="cateParentId">
              <el-tree-select v-model="editForm.data.cateParentId" :data="cateOptions" check-strictly
                              :render-after-expand="false" :props="{ value: 'cateId', label: 'cateName', children: 'children' }"
                              placeholder="请选择父分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属命名空间" prop="cateNamespace">
              <el-select v-model="editForm.data.cateNamespace" placeholder="请选择命名空间" clearable>
                <el-option v-for="dict in cateNamespaceOptions" :key="dict.dictValue" :label="dict.dictLabel"
                           :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类标签" prop="cateLabel">
              <el-input v-model="editForm.data.cateLabel" placeholder="请输入分类标签" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="editForm.data.remark" placeholder="请输入备注" type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4 }" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import { search, insertCateInfo, deleteByIds, updateById, selectById } from '@uni/api/uni/category/info'
import { debounceWrapper } from '@/utils/zmids'

export default {
  // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
  name: 'UniCategoryInfo',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 命名空间字典
      cateNamespaceOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 分类编码
        cateCodeLike: '',
        // 分类名称
        cateNameLike: '',
        // 所属命名空间
        cateNamespaceLike: '',
        // 分类标签
        cateLabelLike: ''
      },
      // 分类树选项
      cateOptions: [],
      editForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 是否修改操作
        isModify: false,
        // 表单参数
        data: {},
        // 规则
        rules: {
          // 分类编码
          cateCode: [
            { required: true, message: '分类编码不可以为空', trigger: 'blur' },
            { min: 1, max: 32, message: '分类编码的长度最多 32 个字符', trigger: 'blur' }
          ],
          // 分类名称
          cateName: [
            { required: true, message: '分类名称不可以为空', trigger: 'blur' },
            { min: 1, max: 128, message: '分类名称的长度最多 128 个字符', trigger: 'blur' }
          ],
          // 父分类ID
          cateParentId: [{ required: true, message: '父分类ID不可以为空', trigger: 'blur' }],
          // 所属命名空间
          cateNamespace: [{ required: true, message: '所属命名空间不可以为空', trigger: 'change' }],
          // 分类标签
          cateLabel: [
            { required: true, message: '分类标签不可以为空', trigger: 'blur' },
            { min: 1, max: 32, message: '分类标签的长度最多 32 个字符', trigger: 'blur' }
          ]
        }
      }
    }
  },
  created() {
    // 查询列表
    this.getList()
    // 初始化字典
    this.getDicts('uni_cate_namespace').then((response) => {
      this.cateNamespaceOptions = response.data
    })
  },
  methods: {
    // 查询列表
    getList: debounceWrapper(function () {
      this.loading = true
      search(this.queryParams).then((response) => {
        this.dataList = response.data
        this.total = response.data.total
        this.loading = false
      })
    }),
    /** 获取分类树选项 **/
    getTreeSelect() {
      this.cateOptions = []
      const cate = { cateId: '0', cateName: '所有分类', children: [] }
      cate.children = this.dataList
      this.cateOptions.push(cate)
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 表单重置
    reset() {
      this.editForm.isModify = false
      this.editForm.data = {
        // 分类编码
        cateCode: '',
        // 分类名称
        cateName: '',
        // 所属命名空间
        cateNamespace: '',
        // 分类标签
        cateLabel: '',
        // 父分类ID
        cateParentId: '',
      }
      // 重置字段校验
      this.$refs.formRef && this.$refs.formRef.clearValidate()
      this.resetForm('formRef')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 所有选中的ID
      this.ids = selection.map((item) => item.cateId)
      // 激活多选删除
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd(row) {
      this.reset()
      this.getTreeSelect()
      if (row != null && row.cateParentId) {
        this.editForm.data.cateParentId = row.cateId
        this.editForm.data.cateNamespace = row.cateNamespace
      } else {
        this.editForm.data.cateParentId = '0'
      }
      this.editForm.open = true
      this.editForm.isModify = false
      this.editForm.title = '新增分类信息表'
    },
    // 删除按钮操作
    handleDelete: debounceWrapper(function (row) {
      const deleteIds = row ? row.cateId : this.ids.join(',')
      deleteByIds(deleteIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () { })
    }),
    // 修改按钮操作
    handleUpdate: debounceWrapper(function (row) {
      this.reset()
      this.getTreeSelect()
      selectById(row.cateId).then((response) => {
        this.editForm.data = response.data
        this.editForm.open = true
        this.editForm.isModify = true
        this.editForm.title = '修改分类信息表'
      })
    }),
    // 提交按钮
    submitForm: debounceWrapper(function () {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          // 创建者
          delete this.editForm.data.createBy
          // 创建时间
          delete this.editForm.data.createTime
          // 更新者
          delete this.editForm.data.updateBy
          // 更新时间
          delete this.editForm.data.updateTime

          const ifUpdate = this.editForm.isModify
          const promise = ifUpdate ? updateById(this.editForm.data) : insertCateInfo(this.editForm.data)
          promise.then((response) => {
            if (response.data === 1) {
              this.msgSuccess(ifUpdate ? '修改成功' : '新增成功')
              this.editForm.open = false
              this.getList()
            }
          })
        }
      })
    }),
    // 取消按钮
    cancel() {
      this.editForm.open = false
      this.reset()
    }
  }
}
</script>

<style lang="scss" scoped></style>
